package com.wy.war.common;


import com.alibaba.fastjson.JSON;
import com.wy.common.BaseCommonController;
import com.wy.constant.CookieConst;
import com.wy.dto.war.UserAccountDto;
import com.wy.service.ex.IUserAccountExService;
import com.wy.util.CookieUtil;
import com.wy.util.EncryptUtil;
import com.wy.util.RedisUtil;
import com.wy.war.constant.WarRedisConst;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

public class BaseController extends BaseCommonController {

	@Autowired
	private IUserAccountExService userAccountExService;

	protected UserAccountDto getUserDto() throws Exception {
		Long id = Long.valueOf(getCookieValue());
		String key = WarRedisConst.USER_KEY + id;
		UserAccountDto userAccountDto  = null;
		if(!RedisUtil.getInstance().exists(key)){
			userAccountDto = userAccountExService.findUserAccountDtoById(id);
			if(null!=userAccountDto){
				RedisUtil.getInstance().set(key, JSON.toJSONString(userAccountDto), 5L, TimeUnit.HOURS);
			}
		} else {
			userAccountDto = JSON.parseObject(RedisUtil.getInstance().get(key).toString(),UserAccountDto.class);
		}
		return userAccountDto;
	}

	protected void setUserDto(UserAccountDto userAccountDto) throws Exception {
		if(null!=userAccountDto){
			String key = WarRedisConst.USER_KEY + userAccountDto.getId();
			RedisUtil.getInstance().set(key, JSON.toJSONString(userAccountDto));
		}
	}

	protected String getCookieValue() throws Exception{
		return EncryptUtil.decode(CookieUtil.getCookieValue(request.getCookies(), CookieConst.WY_CMS_COOKIE_NAME));
	}

}